﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
//using System.Windows.Shapes;

namespace Infusion.Silverlight.Controls.OpenOfficeXML.WordProcessing
{
    #region : Document :
    public class Document
    {
        /* DOCX Document Structure          (Class)
         * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         * 
         *  documentName.docx
         *      |
         *      |- _rels
         *      |   |
         *      |   \- .rels                [TODO]
         *      |
         *      |- docProps
         *      |   |
         *      |   |- app.xml              (ExtendedPropertiesPart)
         *      |   \- core.xml             (CorePropertiesPart)
         *      |
         *      |- word
         *      |   |
         *      |   |- _rels
         *      |   |   |
         *      |   |   \- document.xml     [TODO]
         *      |   |
         *      |   |- theme
         *      |   |   |
         *      |   |   \- theme1.xml       [TODO]
         *      |   |
         *      |   |- document.xml         [TODO]
         *      |   |- fontTable.xml        (FontTablePart)
         *      |   |- settings.xml         (SettingsPart)
         *      |   |- styles.xml           (StylesPart)
         *      |   \- webSettings.xml      (WebSettingsPart)
         *      |
         *      \- [Content_Types].xml      [TODO]
         */

        private const string defaultDocumentNameFormat = "Document{0}.docx";

        private IsolatedStorageFile isoStore;
        private string name;
        private bool initialised = false;
        private bool saved = false;
        private List<OpenXmlPart> parts;

        public Document()
        {
        }

        public void CreateNew()
        {
            isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            List<string> currentDocumentDirs = new List<string>(isoStore.GetDirectoryNames("Document*"));
            
            int nextAvailableNumber = 1;
            bool foundNextNumber = false;
            
            while (!foundNextNumber)
            {
                if (!currentDocumentDirs.Contains(string.Format(defaultDocumentNameFormat, nextAvailableNumber)))
                    foundNextNumber = true;
                else
                    nextAvailableNumber++;
            }

            name = string.Format(defaultDocumentNameFormat, nextAvailableNumber);
            isoStore.CreateDirectory(name);

            parts = new List<OpenXmlPart>();
            parts.Add(new ExtendedPropertiesPart());
            parts.Add(new CorePropertiesPart());
            parts.Add(new FontTablePart());
            parts.Add(new SettingsPart());
            parts.Add(new StylesPart());
            parts.Add(new WebSettingsPart());

            InternalSave();
            initialised = true;

            //using (MemoryStream zippedMemoryStream = new MemoryStream())
            //{
            //    using (ZipOutputStream zipOutputStream = new ZipOutputStream(zippedMemoryStream))
            //    {
            //        zipOutputStream.SetLevel(9);
            //        byte[] buffer;

            //        using (MemoryStream file = new MemoryStream(Encoding.UTF8.GetBytes("simon")))
            //        {
            //            buffer = new byte[file.Length];
            //            file.Read(buffer, 0, buffer.Length);
            //        }

            //        ZipEntry entry = new ZipEntry(name + ".xml");
            //        zipOutputStream.PutNextEntry(entry);
            //        zipOutputStream.Write(buffer, 0, buffer.Length);
            //        zipOutputStream.Finish();
            //    }

            //    try
            //    {
            //        byte[] bytes = zippedMemoryStream.ToArray();

            //        IsolatedStorageFileStream fileStream = isoStore.OpenFile(name + ".zip", FileMode.Create, FileAccess.Write);
            //        fileStream.Write(bytes, 0, bytes.Length);
            //        fileStream.Flush();
            //        fileStream.Close();
            //    }
            //    catch (IsolatedStorageException)
            //    {
            //    }
            //}
        }

        internal void InternalSave()
        {
            foreach (OpenXmlPart part in parts)
            {
                string dirPath = Path.Combine(name, part.TargetPath);
                if (!isoStore.DirectoryExists(dirPath))
                {
                    isoStore.CreateDirectory(dirPath);
                }

                string filePath = Path.Combine(dirPath, part.TargetName) + part.TargetFileExtension;
                if (!isoStore.FileExists(filePath))
                {
                    isoStore.CreateFile(filePath);
                }

                //call each part to save
            }
        }

        public void Save()
        {
            InternalSave();
            saved = true;
        }
    }
    #endregion
}